package com.yilin.xbr.core.base;

import com.yilin.xbr.core.exception.BusinessException;
import org.apache.log4j.Logger;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public abstract class BaseController {
    private Logger logger = Logger.getLogger(BaseController.class);

    public static int AUTH_ERR_CODE = 885;
    public static int INIT_USER_ERR_CODE = 886;
    public static int NO_PASS_ERR_CODE = 888;
    public static int NO_LOGIN_ERR_CODE = 1001;
    public static int FAIL_CODE = -1;
    public static int SUCCESS_CODE = 0;


    protected HttpServletRequest request;
    protected HttpServletResponse response;
    protected HttpSession session;

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value = HttpStatus.OK)
    @ResponseBody
    public Map<String, Object> handleException(Exception ex, HttpServletRequest request) {
        String msg;int code = FAIL_CODE;
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            msg = businessException.getMessage();
            code = businessException.getCode();
        } else {
            msg = ex.getMessage();
            String[] args = msg.split("\r\n");
            if (args.length > 1) {
                msg = args[0];
                int index = msg.indexOf("Exception:");
                if (index != -1) {
                    msg = msg.substring(index + 10);
                }
            }
            if (ex instanceof RuntimeException && ex.getMessage().contains("BusinessException")){
                logger.error("------------【业务错误："+msg+"】------------");
            }else{
                if (logger.isInfoEnabled()) {
                    logger.error("×××××××××××××【警告：小镖人服务器发生严重错误,请立即处理】×××××××××××××");
                    logger.error("×××××××××××××【异常信息："+ex.getMessage()+"】×××××××××××××");
//                    ex.printStackTrace();
                }
            }
        }
        return jsonView(code, msg);
    }

    /**
     * 无数据标准返回
     */
    protected Map<String, Object> jsonView(boolean success, String message) {
        return jsonView(success?SUCCESS_CODE:FAIL_CODE,success, message, null, true,null);
    }

    /**
     * 含数据标准返回
     */
    protected Map<String, Object> jsonView(boolean success, String msg, Object data) {
        return jsonView(success?SUCCESS_CODE:FAIL_CODE,success, msg, data, true,null);
    }

    /**
     * 无数据含返回码
     */
    protected Map<String, Object> jsonView(int code, String msg) {
        return jsonView(code,code==SUCCESS_CODE, msg, null, true,null);
    }

    /**
     * 含数据含返回码 移动端
     */
    protected Map<String, Object> jsonView(int code, boolean success, String msg, Object data) {
        return jsonView(code,success, msg, data, true,null);
    }

    /**
     * 含数据含返回码 后台
     */
    protected Map<String, Object> jsonView(int code, String msg,  Object data) {
        return jsonView(code,code==SUCCESS_CODE, msg, data, true,null);
    }

    /**
     * 含数据不含返回码 （不）加密
     */
    protected Map<String, Object> jsonView( boolean success, String msg, Object data,boolean isEncrypt) {
        return jsonView(success?SUCCESS_CODE:FAIL_CODE,success, msg, data, isEncrypt,null);
    }

    /**
     * 含数据 含TOKEN
     */
    protected Map<String, Object> jsonView( boolean success, String msg,Object data,  String token) {
        return jsonView(success?SUCCESS_CODE:FAIL_CODE,success, msg, data, true,token);
    }
    /**
     * APP全参数返回
     */
    protected Map<String, Object> jsonView(int code, boolean success, String msg,Object data, boolean isEncrypt, String token) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("success", success);
        map.put("msg", msg);
        map.put("data", data);
        map.put("token", token);
        map.put("isEncrypt", isEncrypt);
        return map;
    }

    /**
     * WEB LAYUI 专用TAB分页列表数据返回
     */
    protected Map<String, Object> jsonViewPage(int code, String msg, Map<String, Object> pageDataMap) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("msg", msg);
        map.put("success", code==SUCCESS_CODE);
        map.put("count", pageDataMap.get("total"));
        if (pageDataMap.get("list")!=null){
            map.put("data", pageDataMap.get("list"));
        }
        if (pageDataMap.get("rows")!=null){
            map.put("data", pageDataMap.get("rows"));
        }
        map.put("isEncrypt", true);
        return map;
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
    }

}
